$(document).ready(function() {


    //密码确认
    $('#repwd').change(function () {
        var pwd = $('#pwd').val();
        var repwd = $('#repwd').val();
        if (pwd != repwd) {
            alert('两次密码不一致！');
            $("#repwd").val('');
        }
    });

    //点击注册
    $('#submit').click(function () {

        if(!Form_Data_Validate()){
            return false;
        }

        var text = $("#signin").serialize();
        var role = $("input[name='role']:checked").val();
        var url = "";

        if (role == "student") {
            url = "http://localhost:8080/are_you_learn/studentRegist";
        } else {
            url = "http://localhost:8080/are_you_learn/teacherRegist";
        }


        $.ajax({
            url: url,
            type: "POST",
            async:false,
            data: text,
            xhrFields: {withCredentials: true},
            success: function (result) {
                if (result.code == 200) {
                    alert("注册成功！")
                } else {
                    alert(result.extend.msg)
                }
                //	页面跳转到登陆页面
                window.location.href='signup.html';
            }

        });

    });

    //表单数据验证
    function Form_Data_Validate() {

        var bool = false;
        var num = $("#num").val();
        var email=$('#email').val();
        var pwd=$('#pwd').val();
        var repwd=$('#repwd').val();
        var name=$('#name').val();
        var role = $("input[name='role']:checked").val();

        //1、为空检验
        if (num == '' || email == '' || pwd == '' || repwd == '' || name == '') {
            alert('不能有空值！');
            return bool;
        }

        //2、格式检验
        var reg =/^[0-9]{6,12}$/;
        if(!reg.test(num)){
            alert("请输入正确的学号/工号");
            $("#num").val('');
            return bool;
        }
        reg = /^[\u2E80-\u9FFF]{2,5}/;
        if(!reg.test(name)){
            alert("请输入正确的姓名");
            $("#name").val('');
            return bool;
        }
        reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
        if(!reg.test(email)){
            alert("请输入正确的邮箱");
            $("#email").val('');
            return bool;
        }

        //3、学号/工号查重
        var url = "";
        if (role == "student") {
            url = "http://localhost:8080/are_you_learn/findStudent";
        } else {
            url = "http://localhost:8080/are_you_learn/findTeacher";
        }
        $.ajax({
            url:url,
            type:"POST",
            async:false,
            data:"username="+num,
            success:function (result) {
                if(result.extend.flag == true){
                    alert("该学号/工号已存在");
                }else {
                    bool = true;
                }
            }

        });

        return bool;
    }
    
});


